package com.learnyou.server.xingzuo.biz.helper;

import com.learnyou.server.xingzuo.dto.pet.BehaviorSeparatorDTO;
import com.learnyou.server.xingzuo.dto.pet.BehaviorTimelineDTO;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BehaviorStatisticHelper {


    /**
     * 设定的间隔时长, 默认5分钟
     */
    private int timeSeparator = 5*60;

    public BehaviorStatisticHelper(int timeSeparator) {
        this.timeSeparator = timeSeparator;
    }

    /**
     * 按指定间隔统计行为
     * @param behaviorTimelines
     */
    public LinkedList<BehaviorSeparatorDTO> statistic(int currentStartTime, List<BehaviorTimelineDTO> behaviorTimelines){
        LinkedList<BehaviorSeparatorDTO> behaviorSeparators = new LinkedList<BehaviorSeparatorDTO>();
        int currentEndTime=0, timeCount=0;
        List<Integer> currentBehaviors = new ArrayList<>();
        for (int i = 0; i < behaviorTimelines.size(); i++) {
            BehaviorTimelineDTO timelineDTO = behaviorTimelines.get(i);
            currentBehaviors.addAll(timelineDTO.getBehavior());
            timeCount+=timelineDTO.getTime();
            currentEndTime = currentStartTime+timeCount;
            if (timeCount>=timeSeparator){
                behaviorSeparators.add(BehaviorSeparatorDTO.builder().startTime(currentStartTime).endTime(currentEndTime).behaviors(currentBehaviors).build());
                //下一个统计周期初始化
                currentBehaviors = new ArrayList<>();
                currentStartTime = currentEndTime;
                timeCount = 0;
            }
        }
        if (timeCount>0){
            behaviorSeparators.add(BehaviorSeparatorDTO.builder().startTime(currentStartTime).endTime(currentEndTime).behaviors(currentBehaviors).build());
        }
        return behaviorSeparators;
    }

    /**
     * 获取列表中出现次数最多的行为
     * @param behaviors
     * @return
     */
    public Integer getMaxCountBehavior(List<Integer> behaviors) {
        int behavior=0;
        long behaviorCount=0;
        //每个行为出现次数汇总
        Map<Integer, Long> behaviorCountMap = behaviors.stream().collect(Collectors.groupingBy(t -> t, Collectors.counting()));
        for (Integer key : behaviorCountMap.keySet()) {
            Long v = behaviorCountMap.get(key);
            if (v>behaviorCount){
                behavior=key;
                behaviorCount = v;
            }
        }
        return behavior;
    }
}
